package com.think.teaching.controller;

import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.think.common.model.Result;
import com.think.common.utils.Common;
import com.think.teaching.model.ConfigData;
import com.think.teaching.service.impl.ConfigDataServiceImpl;

@RestController
@ResponseBody
public class WebSiteController {

	@Autowired
	private RedisTemplate redisTemplate;
	
	@Value("${platform.website}")
	public String WebSiteSettingKey;
	
	@Autowired
	private ConfigDataServiceImpl configDataServiceImpl;
	
	@PostMapping("v1/admin/website")
	public Result setWebSiteSetting(@RequestParam String config) {
		ValueOperations valueOperations = redisTemplate.opsForValue();
        /*设置缓存*/
        valueOperations.set(WebSiteSettingKey+ "WEB_SITE_SETTING",config);
    	ConfigData data = new ConfigData();

        data.setKey("WEB_SITE_SETTING");
    	data.setData(config);
    	data.setCreatedBy(Common.GetCurrentAuthor().getUserId());
    	data.setUpdatedBy(Common.GetCurrentAuthor().getUserId());
    	configDataServiceImpl.saveConfigData(data);
        return Result.success();
	}
	
	@GetMapping("v1/open/website")
	public Result getWebSiteSetting() {
		ValueOperations valueOperations = redisTemplate.opsForValue();
        /*设置缓存*/
        Object res = valueOperations.get(WebSiteSettingKey+"WEB_SITE_SETTING");
        if (res != null) {
        	return Result.success(res);
		}
        else {
        	ConfigData data = configDataServiceImpl.getConfigData("WEB_SITE_SETTING");
        	return Result.success(data != null? data.getData():"");
		}

	}
	
	@GetMapping("v1/open/websiteload")
	public Result loadWebSiteSetting() {
		ValueOperations valueOperations = redisTemplate.opsForValue();
        /*设置缓存*/
        Object res = valueOperations.get(WebSiteSettingKey+"WEB_SITE_SETTING");
        if (res != null) {
        	ConfigData data = new ConfigData();
        	data.setKey("WEB_SITE_SETTING");
        	data.setData(res.toString());
        	data.setCreatedBy(Common.GetCurrentAuthor().getUserId());
        	data.setUpdatedBy(Common.GetCurrentAuthor().getUserId());
        	configDataServiceImpl.saveConfigData(data);
		}
        return Result.success();

	}
}
